package com.da.finance;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.googlecode.cswish.annotation.Rest;
import com.googlecode.cswish.exception.ApplicationException;
import com.googlecode.cswish.model.PageInfo;
import com.googlecode.cswish.struts.spring.GenericService;
import com.ra.landlord.LandlordUserService;


@Service
public class DaFinanceCategoryService {

	@Resource
	private GenericService genericService;
	
	@Resource
	private LandlordUserService landlordUserService;
	
	@Rest(type="search")
	public List<DaFinanceCategory> search(DaFinanceCategory model){
		//系统分类必须所有人都可以看
		model.setType(0);
		List<DaFinanceCategory> list=genericService.search(model, 0, 1000, "id", "desc", false).getData();
		model.setType(1);
		list.addAll(genericService.searchAll(model).getData());
		return list;
	}
	
	@Rest(type="add")
	public DaFinanceCategory add(DaFinanceCategory model){
		model.setCreateUser(landlordUserService.getLoginUser());
		model.setType(0);//用户增加的
		model.setCreateDate(new Date());
		return genericService.add(model);
	}
	
	@Rest(type="update")
	public DaFinanceCategory update(DaFinanceCategory model){
		model.setType(0);//用户增加的
		return genericService.merge(model);
	}
	
	@Rest(type="delete")
	public Boolean delete(List<Object> model) {
		
		for (int i = 0; i < model.size(); i++) {
			DaFinanceCategory m = (DaFinanceCategory) genericService.load(model.get(i));
			if (m.getType() == 1) {
				return false;
			}
			DaFinanceStatement statement = new DaFinanceStatement();
			DaFinanceCategory m2 = new DaFinanceCategory();
			m2.setId(m.getId());
			statement.setFinanceCategory(m2);
			PageInfo<DaFinanceStatement> pageInfo = genericService
					.searchAll(statement);
			if (pageInfo.getData().size() > 0) {
				throw new ApplicationException("有财务流水引用了该财务类别，请先删除对应的财务流水！");
			}
		}
		return genericService.deleteList(model);
	}
	
}
